import { createStore } from 'vuex'
import { setLocalStorageState, getLocalStorageItemState } from '../utils/localStorageItem'

export default createStore({
  state: {
    // { shopId: {shopName:'', productList:{ productId: {} }}}
    cartList: getLocalStorageItemState(),
    addressObj: {}
  },
  mutations: {
    countAddChange (states, cartObject) {
      const { shopId, product, conent, num } = cartObject
      const shopNumber = states.cartList[shopId] || { shopName: '', productListObject: {} }
      let productNumber = shopNumber.productListObject[product]
      if (!productNumber) {
        productNumber = conent
        productNumber.count = 0
      }
      if (num > 0) {
        productNumber.iconCheck = true
      }
      productNumber.count += num
      if (productNumber.count < 0) productNumber.count = 0
      shopNumber.productListObject[product] = productNumber
      states.cartList[shopId] = shopNumber
      setLocalStorageState(states)
    },
    changeShopName (states, cartObject) {
      const { shopId, name } = cartObject
      const shopNumber = states.cartList[shopId] || { shopName: '', productListObject: {} }
      shopNumber.shopName = name
      states.cartList[shopId] = shopNumber
      setLocalStorageState(states)
    },
    cartCheckChenge (states, cartObject) {
      const { shopId, productId } = cartObject
      const shopObject = states.cartList[shopId]
      const checkValue = shopObject.productListObject[productId]
      checkValue.iconCheck = !checkValue.iconCheck
      setLocalStorageState(states)
    },
    allCheckchange (states, cartObject) {
      const { shopId } = cartObject
      const shopObject = states.cartList[shopId].productListObject
      let i = ''
      if (shopObject) {
        for (i in shopObject) {
          shopObject[i].iconCheck = true
        }
      }
      setLocalStorageState(states)
    },
    clearChange (states, cartObject) {
      states.cartList[cartObject].productListObject = {}
      setLocalStorageState(states)
    },
    emptyProductFn (states) {
      states.cartList = {}
    },
    addressChange (states, addressData) {
      states.addressObj = addressData
    }
  }
})
